package com.bookworms.helloandengine.game.ui;

import android.content.Intent;
import android.view.KeyEvent;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SplashScreen extends BaseScreen {

    public static final int SPLASH_SCALE = 2;
    public static final int SPLASH_TIME = 500;

    private TextureRegion mSplashTextureRegion;

    @Override
    public void onLoadResources() {
        Texture texture = new Texture(128, 128, TextureOptions.DEFAULT);
        mSplashTextureRegion = TextureRegionFactory.createFromAsset(texture, this, "splash.png", 0, 0);
        mEngine.getTextureManager().loadTexture(texture);
    }

    @Override
    public Scene onLoadScene() {
        Scene mScene = super.onLoadScene();
        final int splashStartX = (mCameraWidth - mSplashTextureRegion.getWidth()) / 2;
        final int splashStartY = (mCameraHeight - mSplashTextureRegion.getHeight()) / 2;
        Sprite splash = new Sprite(splashStartX, splashStartY, mSplashTextureRegion);
        splash.setScale(SPLASH_SCALE);
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
        executor.schedule(getShowMenuTask(), SPLASH_TIME, TimeUnit.MILLISECONDS);
        mScene.setBackground(new ColorBackground(0, 0, 0));
        mScene.attachChild(splash);
        return mScene;
    }

    @Override
    public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
        return pKeyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(pKeyCode, pEvent);
    }

    private Runnable getShowMenuTask() {
        return new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(SplashScreen.this, MainMenuScreen.class);
                startActivity(intent);
                finish();
            }
        };
    }
}